package com.campusflea;

import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.TextView;

import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Message;
import io.rong.message.TextMessage;

public class Chat extends AppCompatActivity {

    public TextView tv1;
    private Handler handler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat);

        RongIMClient.setOnReceiveMessageListener(new MyReceiveMessageListener());
        tv1 = (TextView) findViewById(R.id.tv2);
        handler = new Handler();
        connect("SCwr7sMUjhnqHIzcbCWsEYJHsQ4pY8J5TNCR+OC26eQDAx3rASkssHuqc9xQj04SgKVU1KTIvP55gDpGq5BdfA==");
    }


    /**
     * 建立与融云服务器的连接
     *
     * @param token
     */
    private void connect(String token) {

        if (getApplicationInfo().packageName.equals(App.getCurProcessName(getApplicationContext()))) {
            Log.e("text","--------------1111111111111----------------");
            /**
             * IMKit SDK调用第二步,建立与服务器的连接
             */
            RongIMClient.connect(token, new RongIMClient.ConnectCallback() {


                /**
                 * Token 错误，在线上环境下主要是因为 Token 已经过期，您需要向 App Server 重新请求一个新的 Token
                 */
                @Override
                public void onTokenIncorrect() {

                    Log.d("LoginActivity", "--onTokenIncorrect");
                    Log.e("text","--------------222222222222222----------------");
                }

                /**
                 * 连接融云成功
                 * @param userid 当前 token
                 */
                @Override
                public void onSuccess(String userid) {

                    Log.d("LoginActivity", "--onSuccess---" + userid);
                    Log.e("text","--------------3333333333333----------------");
                }

                /**
                 * 连接融云失败
                 * @param errorCode 错误码，可到官网 查看错误码对应的注释
                 */
                @Override
                public void onError(RongIMClient.ErrorCode errorCode) {

                    Log.d("LoginActivity", "--onError" + errorCode);
                }
            });
        }
    }

    private class MyReceiveMessageListener implements RongIMClient.OnReceiveMessageListener {
        @Override
        public boolean onReceived(Message message, int i) {

            TextMessage msg = (TextMessage) message.getContent();

            final String text = msg.getContent();
            // 构建Runnable对象，在runnable中更新界面
            Runnable runnableUi = new Runnable() {
                @Override
                public void run() {
                    //更新界面
                    tv1.setText("the Content is:" + text);

                }

            };

            handler.post(runnableUi);

            return true;
        }
    }


}